from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import  APIView
from django_redis import get_redis_connection
import pickle,base64
from rest_framework.generics import CreateAPIView
from carts.serializers import CartCreateSerializer, CartListSerializer, CartDlelteSerializer, CartSelectedSerialier
# Create your views here.


# class CarCreateView(CreateAPIView):
#
#     def perform_authentication(self,request):
#
#         pass
#
#     # serializer_class = CartCreateSerializer
#     """
#     请求方式 post
#     请求路径 cart/
#     请求参数 sku_id count select token
#     返回参数 ‘ok’
#     """
from goods.models import SKU


class CarView(APIView):

    def perform_authentication(self,request):

        pass

    def post(self,request):

        data = request.data
        ser = CartCreateSerializer(data=data)
        ser.is_valid(raise_exception=True)
        print(ser.validated_data)
        sku_id = ser.validated_data['sku_id']
        count = ser.validated_data['count']
        selected = ser.validated_data['selected']

        try:
            user = request.user
        except:
            user = None

        if user is not None:
            conn = get_redis_connection('cart')
            conn.hincrby('cart_%s'%user.id,sku_id,count)
            if selected:
                conn.sadd('cart_select_%s'%user.id,sku_id)

            return Response('ok')
        else:
            cart_cookie = request.COOKIES.get('cart_cookie')
            if cart_cookie:
                cart_cookie = pickle.loads(base64.b64decode(cart_cookie))
                # { 15 :{'count':2,'selected':True } }
                cart_dict = cart_cookie.get(sku_id)
                if cart_dict:
                    count += cart_dict['count']

            else:
                cart_cookie = {}

            cart_cookie[sku_id] = {'count':count,'selected':selected }
            cart_cookie = base64.b64encode(pickle.dumps(cart_cookie))
            response = Response('ok')
            response.set_cookie('cart_cookie',cart_cookie,max_age=60*60*24)
            return response


    def get(self,request):

        try:
            user = request.user
        except:
            user = None

        if user is not None:
            sku_dict = { }
            conn = get_redis_connection('cart')
            sku_count = conn.hgetall('cart_%s'%user.id)
            sku_selected = conn.smembers('cart_select_%s' % user.id)
            for sku,count in sku_count.items():
                sku_dict[int(sku)] = { 'count':int(count) , 'selected' : sku in sku_selected }

        else:
            user_cookies = request.COOKIES.get('cart_cookie')
            if user_cookies:
                sku_dict = pickle.loads(base64.b64decode(user_cookies))
            else:
                sku_dict = {}

        skus = SKU.objects.filter(id__in=sku_dict.keys())
        for sku in skus:
            sku.count = sku_dict[sku.id]['count']
            sku.selected = sku_dict[sku.id]['selected']

        ser = CartListSerializer(skus,many=True)
        return Response(ser.data)


    def put(self,request):

        data = request.data
        ser = CartCreateSerializer(data=data)
        ser.is_valid(raise_exception=True)
        sku_id = ser.validated_data['sku_id']
        count = ser.validated_data['count']
        selected = ser.validated_data['selected']

        try:
            user = request.user
        except:
            user = None

        if user is not None:
            conn = get_redis_connection('cart')
            conn.hset('cart_%s'%user.id,sku_id,count)
            if selected:
                conn.sadd('cart_select_%s'%user.id,sku_id)
            else:
                conn.srem('cart_select_%s'%user.id,sku_id)

            return Response(ser.data)
        else:
            cart_cookie = request.COOKIES.get('cart_cookie')
            if cart_cookie:
                cart_dict = pickle.loads(base64.b64decode(cart_cookie))
            else:
                cart_dict = {}

            cart_dict[sku_id] = {
                'count' : count,
                'selected' : selected }

            response = Response(ser.data)

            cart_cookie = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response.set_cookie('cart_cookie',cart_cookie,max_age=60*60*24)

            return response


    def delete(self,request):

        data = request.data
        ser = CartDlelteSerializer(data=data)
        ser.is_valid(raise_exception=True)
        sku_id = ser.validated_data['sku_id']

        try:
            user = request.user
        except:
            user = None

        if user is not None:
            conn = get_redis_connection('cart')
            conn.hdel('cart_%s'%user.id,sku_id)
            conn.srem('cart_select_%s'%user.id,sku_id)

            return Response('ok')
        else:
            cart_cookie = request.COOKIES.get('cart_cookie')
            if cart_cookie:
                cart_dict = pickle.loads(base64.b64decode(cart_cookie))
            # else:
            #     cart_dict = { }

            if cart_dict:
                del cart_dict[sku_id]

            response = Response('ok')
            cart_cookie = base64.b64encode(pickle.dumps(cart_dict))
            response.set_cookie('cart_cookie',cart_cookie,max_age=60*60*24)

            return  response

class CarSelectView(APIView):

    def perform_authentication(self, request):

        pass

    def put(self,request):

        data = request.data
        ser = CartSelectedSerialier(data=data)
        ser.is_valid(raise_exception=True)
        selected = ser.validated_data['selected']

        try:
            user = request.user
        except:
            user = None

        if user is not None:
            conn = get_redis_connection('cart')
            select_dict = conn.hgetall('cart_%s' % user.id)
            for keys in select_dict.keys():
                if selected:
                    conn.sadd('cart_select_%s'%user.id,keys)
                else:
                    conn.srem('cart_select_%s'%user.id,keys)
            return Response(ser.data)
        else:
            response = Response(ser.data)
            cart_cookie = request.COOKIES.get('cart_cookie')
            #{ 'sku_id' :{'count':1,'selectde':True} }
            if cart_cookie:
                cart_dict = pickle.loads(base64.b64decode(cart_cookie))
            else:
                cart_dict = {}

            if cart_dict:
                for keys,key_count_select in cart_dict.items():
                    # if selected:
                    #     key_count_select['selected'] = True
                    # else:
                    #     key_count_select['selected'] = False
                    key_count_select['selected'] = selected

                cart_cookie = base64.b64encode(pickle.dumps(cart_dict))
                response.set_cookie('cart_cookie',cart_cookie,max_age=60*60*24)
            return  response






